import React, { Dispatch, useEffect } from 'react'
import { Tabs, Card, Image, Button } from 'react-vant';
import { useDispatch, useSelector } from 'react-redux'
import { fetchList } from '../../api'
import { ListItem } from '../../store/reducer/listReducer'
import { useNavigate } from 'react-router-dom';
type Props = {}

const Index = (props: Props) => {
	const dispatch = useDispatch()
	const list = useSelector(((state: any) => state.listReducer.list as ListItem[]))
	const userList = useSelector(((state: any) => state.userHistory.list as ListItem[]))
	const navigate = useNavigate()
	const toDetail = (v: ListItem) => {
		navigate({ pathname: `/posts/${v.id}` })
	}
	const onClick = (v: ListItem) => {
		toDetail(v)
		dispatch({ type: 'ADD_USER_HISTORY', payload: v })
	}
	useEffect(() => {
		// 异步action 
		dispatch(async (dispatch: Dispatch<any>) => {
			const resp = await fetchList()
			const { data } = resp.data
			dispatch({ type: 'SET_LIST', payload: data })
		})
	}, [])

	return (

		<div>
			<Button onClick={() => navigate('/city')}>城市： 北京</Button>
			<Tabs align="start">
				<Tabs.TabPane title='推荐'>
					{
						list.length > 0 && list.map((v, i) => {
							return (
								<Card round style={{ marginBottom: 20, backgroundColor: userList.some(item => item.id === v.id) ? '#ccc' : '#fff' }} key={i}
									onClick={() => onClick(v)}
								>
									<Card.Cover>
										<Image src={v.url} />
									</Card.Cover>
									<Card.Header>
										{v.title}
									</Card.Header>
									<Card.Body>{v.desc}</Card.Body>
								</Card>
							)
						})
					}
				</Tabs.TabPane>
				<Tabs.TabPane title='附近'>
					2
				</Tabs.TabPane>
				<Tabs.TabPane title='最新'>
					3
				</Tabs.TabPane>
			</Tabs>
		</div>
	)
}

export default Index